var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var ejs=require('ejs');
//添加session相关的包
var session = require('express-session');
var bodyparser = require('body-parser');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html',ejs.__express);
app.set('view engine', 'html');

app.use(bodyparser.json()); // 使用bodyparder中间件
app.use(bodyparser.urlencoded({ extended: true }));

app.use(cookieParser());
// 使用 session 中间件
app.use(session({
    secret :  'secret', // 对session id 相关的cookie 进行签名
    resave : false,
    saveUninitialized: true, // 是否保存未初始化的会话
    cookie : {
      secure: false,
      maxAge : 1000 * 60*20 // 设置 session 的有效时间，单位毫秒
    },
}));
var accessLogStream =require('fs').createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});
// 自定义日志时间
logger.token('datetime', function(req, res){let date=new Date();return date.toLocaleDateString()+' '+date.toTimeString();});
//配置日志格式，写到文件
app.use(logger(':datetime :method :remote-addr :url :status :res[content-length]字节 :response-time ms',{stream: accessLogStream}));
app.use(express.static(path.join(__dirname, 'public')));

// 学生登录拦截器
app.use('/user',(req, res,next)=>{
  console.log('cookie.username['+req.cookies.username+'] session.userid['+req.session.userid+'] '+new Date().toLocaleTimeString()+' ['+req.method+'] '+req.ip+req.originalUrl);
  if(req.originalUrl!='/user/login'&& req.cookies.username==undefined){
    res.send('学生还没有登录');
  }else{
    next();
  }
});
// 教师登录拦截器
app.use('/admin',(req, res,next)=>{
  console.log('cookie.username['+req.cookies.username+'] session.userid['+req.session.userid+'] '+new Date().toLocaleTimeString()+' ['+req.method+'] '+req.ip+req.originalUrl);
  if(req.originalUrl!='/admin/login'&& req.cookies.username==undefined){
    res.send('教师还没有登录');
  }else{
    next();
  }
});
//路由
app.use('/admin',require('./routes/admin'));
app.use('/user', require('./routes/user'));
app.use('/stu', require('./routes/stu_data'));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  console.error(err.stack);
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error.ejs',{message:res.locals.message,stack:err.stack});
});
module.exports = app;
